package com.google.code.coma.rmi;

import com.google.code.coma.domain.Computer;
import com.google.code.coma.domain.LifeCycleStep;
import com.google.code.coma.domain.Order;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 */
public class ComputerSelector implements EntrySelector<Computer> {
    private List<LifeCycleStep> lifeCycleSteps;
    private Order order;

    public ComputerSelector(LifeCycleStep... lifeCycleSteps) {
        this.lifeCycleSteps = Arrays.asList(lifeCycleSteps);
    }

    public ComputerSelector(Order order, LifeCycleStep... lifeCycleSteps) {
        this(lifeCycleSteps);
        this.order = order;
    }

    @Override
    public List<Computer> selectEntries(List<Computer> allEntries) throws SelectionException {
        if (order != null) {
            return selectByOrderAndLifeCycleSteps(allEntries);
        }

         return selectByLifeCycleSteps(allEntries);
    }

    private List<Computer> selectByLifeCycleSteps(List<Computer> allEntries) throws SelectionException {
        for (Computer computer : allEntries) {
            if (lifeCycleSteps.contains(computer.getCurrent())) {
                return Collections.singletonList(computer);
            }
        }

        throw new SelectionException();
    }

    private List<Computer> selectByOrderAndLifeCycleSteps(List<Computer> allEntries) throws SelectionException {
        List<Computer> selectedComputers = new ArrayList<Computer>();

        for (Computer computer : allEntries) {
            if (computer.getOrder() != null && computer.getOrder().getId().equals(order.getId()) && lifeCycleSteps.contains(computer.getCurrent())) {
                selectedComputers.add(computer);
            }
        }

        return selectedComputers;
    }
}
